package com.itheima.web.filters;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = {"/pages/*","/store/*","/system/*"})
public class AuthenticationFilter implements Filter {
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpServletRequest request = (HttpServletRequest) req;
        //1 从session中获取用户信息
        Object user = request.getSession().getAttribute("user");
        //2 判断是否为null，如果为null就跳转到登录页面
        if (user == null){
            //将访问访问保存到session中，登录成功之后继续访问这个路径
            String sendPath = request.getRequestURI();
            request.getSession().setAttribute("requestURI",sendPath);
            //跳转到登录页面
            response.sendRedirect(request.getContextPath()+"/login.html");
            return;
        }
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

    public void destroy() {
    }

}
